package com.leyou.gateway.task;

import com.leyou.gateway.client.AuthClient;
import com.leyou.gateway.config.JwtProperties;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @author Eric
 * @version v1.0
 * @package com.leyou.gateway.task
 * @date 2019/7/9 18:51
 * @description:
 **/
@Component
@Slf4j
@Getter
public class PrivilegeTokenHolder {


    private String token;

    /**
     * token刷新间隔
     */
    private static final long TOKEN_REFRESH_INTERVAL = 86400000L;

    /**
     * token获取失败后重试的间隔
     */
    private static final long TOKEN_RETRY_INTERVAL = 10000L;


    @Autowired
    private AuthClient authClient;

    @Autowired
    private JwtProperties prop;

    @Scheduled(fixedDelay =TOKEN_REFRESH_INTERVAL)
    public void loadToken() throws InterruptedException {
        while (true) {
            try {
                this.token = authClient.authorization(prop.getApp().getId(), prop.getApp().getSecret());
                log.info("网关刷新token成功！");
                break;
            } catch (Exception e) {
                log.info("网关刷新token失败！",e.getMessage(),e);
            }
            Thread.sleep(TOKEN_RETRY_INTERVAL);
        }

    }
}
